<?php
###
#  Baing PHP 框架 1.0.0
#  http://baing.co/
#
#  Copyright: 白晓阳
#  License: CC BY-NC-SA 4.0
#  https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
###

namespace bai\resource\document;

use bai\feature\BaingException;
use bai\feature\Files;
use bai\resource\application\Logger;


class Php extends \bai\resource\Document
{
    public const TYPE_DEFAULT = 'php';

    public static function load(string $path): ?array
    {
        if (!$path) return null;
        $path = static::fitPath($path);
        if (!static::checkPath($path)) return null;

        try {
            $document = static::setup(['path' => $path]);
            return $document->run();
        } catch (BaingException) {
            return null;
        }
    }

    public static function refresh(string $path, array $content): bool
    {
        if (!$path) return false;
        $name = static::class;
        $path = static::fitPath($path);
        Logger::print("++ Document refresh: $name:$path", Logger::INFO);

        $fullPath = static::preparePath($path);
        if (!$fullPath) return false;
        $dir = dirname($fullPath);
        if (is_writable($dir) || mkdir($dir, 0755, true)) {
            $content = Files::toPhp($content);
            return file_put_contents($fullPath, $content, LOCK_EX) !== false;
        }
        return false;
    }

    public function run()
    {
        ob_start();
        $data = require $this->find('path');
        if ($content = ob_get_clean()) {
            self::$logger->warn("Unexpected output: $content");
        }
        return $data;
    }
}
